// Simple placeholder for a global WebSocket manager
// Replace with a real implementation when backend WS is ready.

let _socket = null
let _connected = false

function connect(url) {
  try {
    if (_connected) return
    if (!url) {
      // no-op: allow page to fallback to its own wsUrl if needed
      return
    }
    const task = uni.connectSocket({ url })
    _socket = task
    task.onOpen(() => { _connected = true; uni.$emit('global-ws-open') })
    task.onClose(() => { _connected = false; uni.$emit('global-ws-close') })
    task.onMessage((evt) => { uni.$emit('global-ws-message', evt) })
    task.onError(() => { _connected = false })
  } catch (e) {
    // keep placeholder silent
  }
}

function isConnected() {
  return !!_connected
}

function getSocket() {
  return _socket
}

function send(payload) {
  try {
    if (!_socket || !_connected) return
    const data = typeof payload === 'string' ? payload : JSON.stringify(payload)
    _socket.send({ data })
  } catch (e) {}
}

export default { connect, isConnected, getSocket, send }
